package ppa.marc.importer.database;

import java.sql.SQLDataException;

import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;

import ppa.marc.domain.SubField;
import ppa.marc.importer.data.DataIntegrityException;

public class JdbcSubFieldInserter implements SubFieldInserter {
	private final JdbcTemplate jdbcTemplate;

	public JdbcSubFieldInserter(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public void insert(SubField subField, int position, long fieldId) throws DataInsertionException, DataIntegrityException {
		try {
			insertToDatabase(subField, position, fieldId);
		} catch(DuplicateKeyException duplicateKeyException) {
			throw new DataIntegrityException("Subfield with internal parent identifier " + fieldId + " and position " + position + " already exists.");
		}
		catch(DataIntegrityViolationException dataIntegrityViolation) {
			throw new DataIntegrityException(resolveErrorMessage(fieldId, dataIntegrityViolation));
		}
	}

	private String resolveErrorMessage(long fieldId, DataIntegrityViolationException dataIntegrityViolation) {
		if(dataIntegrityViolation.contains(SQLDataException.class)) return "Value is too large, it can have at most 9999 characters.";
		return "Parent field with internal identifier " + fieldId + " doesn't exist.";
	}

	private void insertToDatabase(SubField subField, int position, long fieldId) {
		if(subField.getId() == null) {
			jdbcTemplate.update("insert into marc_subfield (position, field_id, value) values (?, ?, ?)", position, fieldId, subField.getValue());
		}
		else {
			jdbcTemplate.update("insert into marc_subfield (marc_id, position, field_id, value) values (?, ?, ?, ?)", subField.getId(), position, fieldId, subField.getValue());
		}
	}
}
